package com.doyens.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doyens.reggie.commons.R;
import com.doyens.reggie.domain.User;
import com.doyens.reggie.service.UserService;
import com.doyens.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 登录功能
    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> map,HttpServletRequest request){
      log.info("登录的信息：" + map);
      // 获取手机号和验证码
        String phone = map.get("phone");
        String inputCode = map.get("code");

        //
         HttpSession session = request.getSession();
        /*  String sessionCode = (String) session.getAttribute(phone);*/


        String sessionCode= (String) redisTemplate.opsForValue().get(phone);

        if(StringUtils.equals(inputCode,sessionCode)){
            // 登录成功
            // 根据手机号做查询
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
            if(user == null){// 说明没有查询 第一次 那就注册
                user=new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user);

            //删除验证码
            redisTemplate.delete(phone);

            return R.success("登录成功");
        }
        return R.error("验证码错误");
    }

    @GetMapping("getCode")
    public R getCode(String phone, HttpServletRequest request){
        // 随机生成验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        // 将手机号和验证码存入session域
       /* HttpSession session = request.getSession();
        session.setAttribute(phone,code);*/

        //短信验证码存入到redis
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);


        // 发短信 控制台
        System.out.println("【瑞吉外卖】您的验证码为：" + code);
        return R.success(code);
    }
}
